java多线程– sleep实现 ( 时间刷新 , 模拟倒计时)

java
Author

dd21

Published

December 5, 2022

package cn.usts.edu.lesson06;

import org.junit.Test;

import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * 时间刷新
 * 模拟倒计时
 * */

public class TimeFlush  {
    // 时间刷新
    public static void main(String[] args) {
        Date date = new Date(System.currentTimeMillis());// 获取系统当前时间
        while (true){
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(date));
            date = new Date(System.currentTimeMillis());//刷新时间
        }
    }
}

模拟倒计时

在这里插入图片描述
 // 模拟倒计时
    @Test
    public void tenSecondFlush(){
        int num = 10;
        while (true){
            if (num <= 0) {
                break;
            }
            try {
                Thread.sleep(1000);
                System.out.println(num--);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }


        }
    }